package tk.mybatis.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.springboot.mapper.*;
import tk.mybatis.springboot.model.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.NumberFormat;
import java.util.*;
import java.util.function.BiConsumer;

/**
 * Created by admin on 2017/4/17.
 */
@Controller
public class CoreController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionsMapper questionsMapper;

    @RequestMapping("")
    public String index(Model model,@ModelAttribute("key") String key){
        return "frame";
    }
    @RequestMapping("/admin")
    public String admin(Model model,HttpSession session){
        model.addAttribute("me",session.getAttribute("me"));
        return "admin";
    }

    private BaseUser getUserById(Integer id){
        BaseUser users = teacherMapper.selectByPrimaryKey(id);
        if(null == users){
            users = studentMapper.selectByPrimaryKey(id);
        }
        if(null == users){
            users = userMapper.selectByPrimaryKey(id
            );
        }
        return users;
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object login(String username, String password, HttpSession session){
        BaseUser users = teacherMapper.selectOne(new Teacher() {
            {
                setUsername(username);
                setPassword(password);
            }
        });
        if(null == users){
            users = studentMapper.selectOne(new Student() {
                {
                    setUsername(username);
                    setPassword(password);
                }
            });
        }
        if(null == users){
            users = userMapper.selectOne(new Users() {
                {
                    setUsername(username);
                    setPassword(password);
                }
            });
        }
        if(null == users){
            return new Message("用户名或者密码错误",false);
        }
        session.setAttribute("me",users);
        return new Message("",true);
    }
    private BaseUser getLoginUser(HttpSession session){
        BaseUser me = (BaseUser)session.getAttribute("me");
        return me;
    }

    @ExceptionHandler
    public String error(Exception e,Model model){
        e.printStackTrace();
        model.addAttribute("msg",e.getMessage());
        return "500";
    }

    @RequestMapping(value = "/standard",method = RequestMethod.GET)
    public String standard(Model model){
        model.addAttribute("list",questionsMapper.selectAll());
        return "standard";
    }
    @RequestMapping(value = "/password",method = RequestMethod.GET)
    public String password(Model model){
        return "password";
    }

    //用户留言，选择对谁留言
    @RequestMapping(value = "/liuyan",method = RequestMethod.GET)
    public String liuyan(Model model){
        model.addAttribute("teachers",teacherMapper.selectAll());
        model.addAttribute("students",studentMapper.selectAll());
        return "liuyan";
    }
    @RequestMapping(value = "/liuyan",method = RequestMethod.POST)
    @ResponseBody
    public Object liuyan(Feedback feedback,HttpSession session,String target){
        if("option2".equals(target)){
            feedback.setType("admin");
        }
        BaseUser user = getLoginUser(session);
        feedback.setCreateTime(new Date());
        feedback.setFromUser(user.getId());

        feedbackMapper.insert(feedback);
        return new Message();
    }

    @Autowired
    private FeedbackMapper feedbackMapper;
    @Autowired
    private NewsMapper newsMapper;

    @RequestMapping(value = "/liuyanMgr",method = RequestMethod.GET)
    public String liuyanMgr(Model model,HttpSession session){
        List<Feedback> list = feedbackMapper.selectAll();
        for(Feedback item:list){
            BaseUser baseUser = null;
            if("st".equals(item.getType())){
                baseUser = studentMapper.selectByPrimaryKey(item.getFromUser());
            }
            else if("ts".equals(item.getType())){
                baseUser = teacherMapper.selectByPrimaryKey(item.getFromUser());
            }
            if(null != baseUser) {
                item.setFromUserName(baseUser.getName());
            }
        }
        model.addAttribute("list",list);
        return "feedback";
    }
    /**查看留言
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/feedback",method = RequestMethod.GET)
    public String feedback(Model model,HttpSession session){
        String type = null;
        BaseUser user = getLoginUser(session);
        Integer to = null;
        if(user.isTeacher()){
            type = "st";
            to = user.getId();
        }
        else if(user.isStudent()){
            type = "ts";
            to = user.getId();
        }
        else{
            type = "admin";
        }
        String finalType = type;
        Integer finalTo = to;

        List<Feedback> list = feedbackMapper.select(new Feedback() {
            {
                setType(finalType);
                setToUser(finalTo);
            }
        });
        for(Feedback item:list){
            BaseUser userById = getUserById(item.getFromUser());
            if(null != userById) {
                item.setFromUserName(userById.getName());
            }
        }
        model.addAttribute("list",list);
        return "feedback";
    }
    @RequestMapping(value = "/feedback/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Object feedback(@PathVariable Integer id){
        feedbackMapper.deleteByPrimaryKey(id);
        return new Message();
    }

    @RequestMapping(value = "/news",method = RequestMethod.GET)
    public String news(Model model){
        model.addAttribute("list",newsMapper.selectAll());
        return "news";
    }
    @RequestMapping(value = "/news",method = RequestMethod.POST)
    @ResponseBody
    public Object news(News news){
        news.setCreateTime(new Date());
        newsMapper.insertSelective(news );
        return new Message();
    }
    @RequestMapping(value = "/news/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Object news(@PathVariable Integer id){
        newsMapper.deleteByPrimaryKey(id);
        return new Message();
    }


    @RequestMapping(value = "/help",method = RequestMethod.GET)
    public String help(Model model){
        return "help";
    }

    @Autowired
    private AnswersMapper answersMapper;
    @Autowired
    private CourseMapper courseMapper;
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String test(Model model,HttpSession session,String module){
        if(StringUtils.isEmpty(module)){
            module = "1";
        }

        BaseUser user = getLoginUser(session);
        if(user.isStudent()){
            Student student = (Student)user;
            Set<Teacher> teachers = new HashSet<>();
            List<Course> courses = courseMapper.select(new Course() {
                {
                    setClassId(student.getCid());
                }
            });
            courses.forEach(course -> teachers.add(teacherMapper.selectByPrimaryKey(course.getTeacherId())));
            model.addAttribute("target",teachers);
        }
        else if(user.isTeacher()){
            Teacher teacher = (Teacher) user;
            Set<Student> students = new HashSet<>();
            List<Course> courses = courseMapper.select(new Course() {
                {
                    setTeacherId(teacher.getId());
                }
            });
            courses.forEach(course ->
                students.addAll(studentMapper.select(new Student(){
                    {
                        setCid(course.getClassId());
                    }
                }))
            );
            model.addAttribute("target",students);
        }
        String finalModule = module;
        model.addAttribute("module",module);
        List<Questions> list = questionsMapper.select(new Questions() {
            {
                setType(getLoginUser(session).getType());
                setModule(finalModule);
            }
        });
        for(Questions item:list){
            Answers answers = answersMapper.selectOne(new Answers() {
                {
                    setQid(item.getId());
                    setUserId(getLoginUser(session).getId());
                }
            });
            if(null != answers) {
                item.setAnswer(answers.getOption());
            }
        }
        Feedback feedback = feedbackMapper.selectOne(new Feedback(){
            {
                setFromUser(user.getId());
                setToUser(user.getId());
                setType("self");
            }
        });
        if(null != feedback) {
            model.addAttribute("self_feedback",feedback.getContent());
        }
        model.addAttribute("list",list);
        return "test";
    }

    @RequestMapping(value = "/self_feedback",method = RequestMethod.POST)
    @ResponseBody
    public Object self_feedback(String content,HttpSession session){
        BaseUser user = getLoginUser(session);
        feedbackMapper.delete(new Feedback(){
            {
                setFromUser(user.getId());
                setToUser(user.getId());
                setType("self");
            }
        });
        feedbackMapper.insertSelective(new Feedback(){
            {
                setFromUser(user.getId());
                setToUser(user.getId());
                setType("self");
                setContent(content);
            }
        });
        return new Message();
    }

    @RequestMapping(value = "/answer",method = RequestMethod.POST)
    @ResponseBody
    public Object answer(HttpServletRequest request, HttpSession session){
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach(new BiConsumer<String, String[]>() {
            @Override
            public void accept(String s, String[] strings) {
                if(s.startsWith("q_")){
                    Integer qid = Integer.parseInt(s.split("_")[1]);
                    Answers answers = new Answers();
                    answers.setUserId(getLoginUser(session).getId());
                    answers.setOption(strings[0]);
                    answers.setQid(qid);
                    answersMapper.delete(new Answers(){
                        {
                            setUserId(getLoginUser(session).getId());
                            setQid(qid);
                        }
                    });
                    answersMapper.insertSelective(answers);

                }
            }
        });
        return new Message();
    }

    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public String info(Model model,HttpSession session,String module){
        BaseUser users = getLoginUser(session);
        String type="teacher";
        if(users.getType().equals("teacher")){
            type = "student";
        }
        if(StringUtils.isEmpty(module)){
            module = "1";
        }
        model.addAttribute("module",module);
        final String type1 = type;
        final String module1 = module;
        List<Questions> list = questionsMapper.select(new Questions() {
            {
                setType(type1);
                setModule(module1);
            }
        });
        for(Questions item:list){
            double total = answersMapper.selectCount(new Answers(){
                {
                    setQid(item.getId());
                }
            });
            if(0 < total){
                int a = answersMapper.selectCount(new Answers(){
                    {
                        setQid(item.getId());
                        setOption("1");
                    }
                });
                int b =answersMapper.selectCount(new Answers(){
                    {
                        setQid(item.getId());
                        setOption("2");
                    }
                });
                int c = answersMapper.selectCount(new Answers(){
                    {
                        setQid(item.getId());
                        setOption("3");
                    }
                });
                item.setRate1(toFixDouble(a/total));
                item.setRate2(toFixDouble(b/total));
                item.setRate3(toFixDouble(c/total));
            }
        }
        model.addAttribute("list",list);
        return "info";
    }

    private double toFixDouble(double d){
        NumberFormat fmt = NumberFormat.getInstance();
        fmt.setMaximumFractionDigits(2);
        return Double.parseDouble(fmt.format(d));
    }
    @RequestMapping(value = "/standard",method = RequestMethod.POST)
    @ResponseBody
    public Object standard(Questions questions){
        questions.setCreateTime(new Date());
        questionsMapper.insertSelective(questions);
        return new Message();
    }
    @RequestMapping(value = "/standard/del/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Object standard(@PathVariable Integer id){
        questionsMapper.deleteByPrimaryKey(id);
        return new Message();
    }

    @RequestMapping("/download/{id}")
    public void downloadFile(@PathVariable String id, HttpServletResponse response) throws IOException {

        String fileName = null;
        byte[] content  = null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

        OutputStream os = response.getOutputStream();
        os.write(content);

        os.close();
    }

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private ClassesMapper classesMapper;

    @RequestMapping(value = "/regStudent",method = RequestMethod.POST)
    @ResponseBody
    public Object register(Student student){
        studentMapper.insertSelective(student);
        return new Message();
    }
    @RequestMapping(value = "/regTeacher",method = RequestMethod.POST)
    @ResponseBody
    public Object register(Teacher teacher){
        teacherMapper.insertSelective(teacher);
        return new Message();
    }

    @RequestMapping(value = "regStudent",method = RequestMethod.GET)
    public String regStudent(Model model){
        model.addAttribute("classes",classesMapper.selectAll());
        return "regStudent";
    }
    @RequestMapping(value = "regTeacher",method = RequestMethod.GET)
    public String regTeacher(Model model){
        model.addAttribute("classes",classesMapper.selectAll());
        return "regTeacher";
    }


    @RequestMapping(value = "/classes",method = RequestMethod.POST)
    @ResponseBody
    public Object classes(Classes classes){
        classesMapper.insertSelective(classes);
        return new Message();
    }

    @RequestMapping(value = "/classes",method = RequestMethod.GET)
    public String classes(Model model){
        model.addAttribute("list",classesMapper.selectAll());
        return "classes";
    }

}
